import {
  Card,
  Breadcrumb,
  Form,
  Select,
  Button,
  Input,
  Space,
  Radio,
  Upload,
  message,
} from "antd"
import ReactQuill from "react-quill"
import "react-quill/dist/quill.snow.css"
import { Link } from "react-router-dom"
import { useChannels } from "@/utils/customHooks"
import styles from "./index.module.scss"
import { PlusOutlined } from "@ant-design/icons"
import { useState, useEffect } from "react"
import { addArticle, editArticle, getArticle } from "@/store/actions/article"
import { useDispatch } from "react-redux"
import { useHistory, useParams } from "react-router-dom"
const Publish = () => {
  const params = useParams()
  const [form] = Form.useForm() // 得到form对象
  // 频道数据
  const history = useHistory()
  const dispatch = useDispatch()
  const channels = useChannels()
  const [type, setType] = useState(1) // 默认值 单图 三图 无图  1 3  0
  const [fileList, setFileList] = useState([]) // 让fileList受控
  const onTypeChange = (e) => {
    setType(e.target.value)
    setFileList([]) // 只要切换图片  就将图片列表清空
  }
  useEffect(() => {
    const getArticleInfo = async () => {
      // 获取文章详情的数据
      if (params.id) {
        // 获取文章详情数据
        const { data } = await dispatch(getArticle(params.id))
        form.setFieldsValue({
          title: data.title,
          channel_id: data.channel_id,
          content: data.content,
        }) // 设置表单的值
        // 设置 type fileList
        setType(data.cover.type)
        setFileList(data.cover.images.map((url) => ({ url })))
      } else {
        // 当前模式是新增情况下  默认清空上传列表 重置表单吧
        setType(1)
        setFileList([])
        // form重置表单
        form.resetFields() // 重新设置表单
      }
    }
    getArticleInfo()
  }, [dispatch, params, form])
  // 点击发表文章
  const onFinish = async (values, draft) => {
    // values是通过校验的数据
    if (type !== fileList.length) {
      // 1 3 0 => [1] [1,2,3] []
      message.warning("封面类型和所上传图片不符合")
      return
    }
    const data = {
      ...values,
      cover: {
        type,
        // images
        // 两种场景 1 新增 => fileList => [{ response: { data: { url } } }]
        // 编辑场景 2 数据库 => fileList =>  [{ url }]
        images: fileList.map((item) => item?.response?.data?.url || item.url),
      },
    }
    if (params.id) {
      // 编辑场景
      await dispatch(editArticle({ id: params.id, ...data }, draft))
    } else {
      // 新增场景
      await dispatch(addArticle(data, draft)) // 调用发布接口
    }
    message.success("操作成功")
    history.push("/home/article")
    // 调用action => 数据
    // cover: { type: 1/3/0, images: ["","", ""]  }
  }
  // 存草稿
  const saveDraft = async () => {
    try {
      const values = await form.validateFields() // 校验表单-返回表单的值
      onFinish(values, true) // 继续走原来的逻辑
    } catch (error) {
      // console.log("校验有问题")
    }
  }
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              <Link to="/home/article">内容管理</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>发布文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form form={form} labelCol={{ span: 4 }} onFinish={onFinish}>
          <Form.Item
            label="文章标题："
            name="title"
            rules={[{ required: true, message: "文章标题不能为空" }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="所属频道："
            name="channel_id"
            rules={[{ required: true, message: "文章频道不能为空" }]}
          >
            <Select style={{ width: 400 }}>
              {channels.map((item) => {
                return (
                  <Select.Option key={item.id} value={item.id}>
                    {item.name}
                  </Select.Option>
                )
              })}
            </Select>
          </Form.Item>
          <Form.Item label="封面：">
            <Radio.Group
              value={type}
              onChange={onTypeChange}
              // onChange={((e) => setType(e.target.value), setFileList([]))}
            >
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
            {(type === 1 || type === 3) && (
              <div style={{ marginTop: 16 }}>
                <Upload
                  name="image"
                  listType="picture-card"
                  action="http://toutiao.itheima.net/v1_0/upload"
                  fileList={fileList}
                  onPreview={() => {}}
                  onChange={({ fileList }) => {
                    // 将上传组件的内容更新到 状态中
                    setFileList(fileList)
                  }}
                >
                  {fileList.length < type ? (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>Upload</div>
                    </div>
                  ) : null}
                </Upload>
              </div>
            )}
          </Form.Item>
          <Form.Item
            label="文章内容"
            name="content"
            initialValue=""
            rules={[{ required: true, message: "文章内容不能为空" }]}
          >
            <ReactQuill placeholder="请输入文章内容"></ReactQuill>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                发表文章
              </Button>
              <Button size="large" onClick={saveDraft}>
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
export default Publish
